import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'
import { Message } from 'element-ui'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})

/**
 * 请求拦截
 */
service.interceptors.request.use(
    async (config: AxiosRequestConfig) => {
        return config
    },
    (err) => {
        return Promise.reject(err)
    }
)

/**
 * 响应拦截
 */
service.interceptors.response.use(
    async (response: AxiosResponse) => {
        return response
    },
    (err) => {
        // 拦截错误处理
        return Promise.reject(err)
    }
)

const apiAxios = async <T>(method: Method, url: string, params: any): Promise<T> => {
    try {
        let res = await service({
            method,
            url,
            data: ['POST', 'PUT'].includes(method.toUpperCase()) ? params : null,
            params: ['GET', 'DELETE'].includes(method.toUpperCase()) ? params : null
        })
        return res.data
    } catch (e) {
        let message = e.message
        if (e.response) {
            if (e.response.statusText) {
                message = e.response.statusText
            }
            if (e.response.data && e.response.data.message) {
                message = e.response.data.message
            }
        }
        Message({
            message,
            type: 'error'
        })
        throw e.response || e
    }
}

export default {
    get<T>(url: string, params: any) {
        return apiAxios<T>('GET', url, params)
    },
    post<T>(url: string, params: any) {
        return apiAxios<T>('POST', url, params)
    },
    put<T>(url: string, params: any) {
        return apiAxios<T>('PUT', url, params)
    },
    delete<T>(url: string, params: any) {
        return apiAxios<T>('DELETE', url, params)
    }
}
